//
//  AFNHttp.m
//  YLNetworkingFrameworks
//
//  Created by Topsun on 16/6/2.
//  Copyright © 2016年 tcl. All rights reserved.
//

#import "AFNHttp.h"

#define requestTimeOut 30.0f

@implementation AFNHttp
@synthesize userInfo            = _userInfo;             // 用户自定义数据结构
@synthesize error               = _error;                // 当前的错误对象
@synthesize url                 = _url;                  // 请求的网络地址
@synthesize responseString      = _responseString;       // 网络请求完成后的字符内容
@synthesize requestMethod       = _requestMethod;        // 网络请求方法
@synthesize headValueDictionary = _headValueDictionary;  // 请求的head对象
@synthesize postValueDictionary = _postValueDictionary;  // 请求的post对象
@synthesize getValueDictionary  = _getValueDictionary;   // 请求的get对象
@synthesize responseData        = _responseData;         // 网络请求完成后的二进制数据


- (AFHTTPSessionManager *) getAFHTTPSessionManager
{
    //1.管理器
    AFHTTPSessionManager * sessionManager = [AFHTTPSessionManager manager];
    
    //2.设定类型. (这里要设置request-response的类型)
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //申明请求的数据是json类型
    sessionManager.requestSerializer=[AFJSONRequestSerializer serializer];
    // 请求超时设定
    sessionManager.requestSerializer.timeoutInterval = requestTimeOut;
    //3.添加请求头
    for (NSString *key in self.headValueDictionary.allKeys)
    {
        [sessionManager.requestSerializer setValue:self.headValueDictionary[key] forHTTPHeaderField:key];
    }
    // 设置请求头User-Agent
    //    [sessionManager.requestSerializer setValue:[[CommonParameterManager shareManager]ObtainUserAgent] forHTTPHeaderField:@"Content-type: application/json"];
    
    return sessionManager;
}

// 启动一个同步请求
- (void) startSynchronou:(CompletionRequest)block
{

}

- (void)startAsynchronous:(CompletionRequest)block
{
    // 获取 AFHTTPSessionManager
    AFHTTPSessionManager * sessionManager = [self getAFHTTPSessionManager];
    
    //4.请求地址
    NSString * requestURL = [NSString stringWithFormat:@"%@",self.url];
    
    //发送HEAD请求
    NSComparisonResult comparisonResult = [self.requestMethod caseInsensitiveCompare:@"HEAD"];
    
    if (comparisonResult == NSOrderedSame)
    {
        [self sendHeadRequest:block AFSessionManager:sessionManager requestRUL:requestURL];
    }
    
    //发送GET请求
    comparisonResult = [self.requestMethod caseInsensitiveCompare:@"GET"];
    
    if (comparisonResult == NSOrderedSame)
    {
        [self sendGetRequest:block AFSessionManager:sessionManager requestRUL:requestURL];
    }
    
    //发送POST请求
    comparisonResult = [self.requestMethod caseInsensitiveCompare:@"POST"];
    
    if (comparisonResult == NSOrderedSame)
    {
        [self sendPostRequest:block AFManager:sessionManager requestRUL:requestURL];
    }
}

/**
 *brief 发送HEAD请求
 *param
 *author 李悦麟
 */
-(void)sendHeadRequest:(CompletionRequest)block AFSessionManager:(AFHTTPSessionManager *)sessionManager requestRUL:(NSString*)requestURL
{
    [sessionManager HEAD:requestURL parameters:self.headValueDictionary success:^(NSURLSessionDataTask * _Nonnull task) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
        block(error);
    }];
}

/**
 *brief 发送GET请求
 *param
 *author 李悦麟
 */
-(void)sendGetRequest:(CompletionRequest)block AFSessionManager:(AFHTTPSessionManager *)sessionManager requestRUL:(NSString*)requestURL
{
    [sessionManager GET:requestURL parameters:self.getValueDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 转换编码方法
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
        // 创建UTF编码对象
        _responseString = [[NSString alloc] initWithData:responseObject encoding:enc];
        block(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
        block(error);
    }];
}

/**
 *brief 发送POST请求,无图片 or 视频音频
 *param
 *author 李悦麟
 */
-(void)sendPostRequest:(CompletionRequest)block AFManager:(AFHTTPSessionManager *)sessionManager requestRUL:(NSString*)requestURL
{
    [sessionManager POST:requestURL parameters:self.postValueDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 转换编码方法
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
        // 创建UTF编码对象
        _responseString = [[NSString alloc] initWithData:responseObject encoding:enc];
        block(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
        block(error);
    }];
}

// 获取返回的响应的字符串
- (NSString*) responseString
{
    return _responseString;
}

// 添加一个Post请求参数
- (void)addPostValue:(id <NSObject>)value forKey:(NSString *)key
{
    if ( value != nil && key != nil ) {
        [self.postValueDictionary setObject:value forKey:key];
    }
    
}

// 添加一个Post请求参数，如果存在则将之前设置的值清楚
- (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key
{
    if ( value != nil && key != nil ) {
        [self.postValueDictionary removeObjectForKey:key];
        
        [self addPostValue:value forKey:key];
    }
    
}

// 添加一个Get请求参数
- (void)addGetValue:(id<NSObject>)value forKey:(NSString *)key
{
    if ( value != nil && key != nil ) {
        [self.getValueDictionary setObject:value forKey:key];
    }
    
}

// 添加一个Get请求参数，如果存在则将之前设置的值清楚
- (void)setGetValue:(id<NSObject>)value forKey:(NSString *)key
{
    if ( value != nil && key != nil ) {
        [self.getValueDictionary removeObjectForKey:key];
        [self addGetValue:value forKey:key];
    }
}

// 添加一个head请求参数
- (void)addHeadValue:(id<NSObject>)value forKey:(NSString *)key
{
    if ( value != nil && key != nil ) {
        [self.headValueDictionary setObject:value forKey:key];
    }
    
}

// 添加一个Head请求参数，如果存在则将之前设置的值清除
- (void)setHeadValue:(id<NSObject>)value forKey:(NSString *)key
{
    if ( value != nil && key != nil ) {
        
        [self.headValueDictionary removeObjectForKey:key];
        
        [self addHeadValue:value forKey:key];
    }
    
}

// 返回Post对象字典
- (NSMutableDictionary*) postValueDictionary
{
    if ( nil == _postValueDictionary ) {
        _postValueDictionary = [[NSMutableDictionary alloc] init];
    }
    return _postValueDictionary;
}

- (NSMutableDictionary*) headValueDictionary
{
    if ( nil == _headValueDictionary ) {
        _headValueDictionary = [[NSMutableDictionary alloc] init];
    }
    return _headValueDictionary;
}

- (NSMutableDictionary*) getValueDictionary
{
    if ( nil == _getValueDictionary ) {
        _getValueDictionary = [[NSMutableDictionary alloc] init];
    }
    
    return _getValueDictionary;
}

@end
